-- LevelTileConfig.lua
-- 关卡切片配置模块 - 完整修正版

local LevelTileConfig = {}

-- 切片基本信息
LevelTileConfig.TILE_SIZE = {width = 2400, height = 1600}
LevelTileConfig.GRID_SIZE = {rows = 5, cols = 10}  -- 5行10列
LevelTileConfig.TOTAL_TILES = 50

-- 切片命名规则
LevelTileConfig.TILE_NAME_PATTERN = "tile_%02d_%02d.png"

-- 基础路径
LevelTileConfig.BASE_PATH = "Image/level-inroom/"

-- 完整关卡尺寸
LevelTileConfig.LEVEL_SIZE = {
    width = 24000,  -- 2400 * 10
    height = 8000   -- 1600 * 5
}

-- 地面高度设置
LevelTileConfig.GROUND_HEIGHT = 320  -- 每个切片底部向上320像素为地面

print("====================================")
print("初始化关卡切片配置")
print("坐标系统：行号从上到下，第1行在最上面")
print("Y坐标公式：y = (5 - row) * 1600")
print("tile_01_01.png 在左上角 (0, 6400)")
print("tile_05_01.png 在左下角 (0, 0)")
print("====================================")

-- 初始化切片位置映射表
LevelTileConfig.tilePositions = {}

for row = 1, LevelTileConfig.GRID_SIZE.rows do
    for col = 1, LevelTileConfig.GRID_SIZE.cols do
        -- 索引计算：从上到下，从左到右
        local index = (row - 1) * LevelTileConfig.GRID_SIZE.cols + col
        
        -- X坐标：从左到右递增（第1列在最左边）
        local x = (col - 1) * LevelTileConfig.TILE_SIZE.width
        
        -- Y坐标：从上到下递减（第1行在最上面y=6400，第5行在最下面y=0）
        -- 使用公式：y = (5 - row) * 1600
        local y = (LevelTileConfig.GRID_SIZE.rows - row) * LevelTileConfig.TILE_SIZE.height
        
        -- 地面Y坐标：从切片底部向上GROUND_HEIGHT像素
        local groundY = y + LevelTileConfig.GROUND_HEIGHT
        
        LevelTileConfig.tilePositions[index] = {
            row = row,
            col = col,
            index = index,
            x = x,
            y = y,
            worldX = x + LevelTileConfig.TILE_SIZE.width / 2,
            worldY = y + LevelTileConfig.TILE_SIZE.height / 2,
            filename = LevelTileConfig.BASE_PATH .. string.format(LevelTileConfig.TILE_NAME_PATTERN, row, col),
            groundY = groundY,
            leftBound = x,
            rightBound = x + LevelTileConfig.TILE_SIZE.width,
            topBound = y + LevelTileConfig.TILE_SIZE.height,
            bottomBound = y
        }
        
        -- 输出关键切片信息用于调试
        if (row == 5 and col == 1) or (row == 1 and col == 1) or (row == 1 and col == 10) then
            print(string.format("切片 %02d_%02d: 索引=%d, 坐标(x=%.1f, y=%.1f), 地面=%.1f, 文件=%s",
                row, col, index, x, y, groundY, LevelTileConfig.tilePositions[index].filename))
        end
    end
end

print("====================================")
print("关卡配置初始化完成，共 " .. LevelTileConfig.TOTAL_TILES .. " 个切片")
print("05_01：左下角，索引=41，坐标(0, 0)")
print("01_01：左上角，索引=1，坐标(0, 6400)")
print("01_10：右上角，索引=10，坐标(21600, 6400)")
print("====================================")

-- 获取切片周围8个方向的邻居
function LevelTileConfig.getNeighbors(row, col)
    local neighbors = {}
    
    -- 定义8个方向
    local directions = {
        {dr = -1, dc = -1},  -- 左上
        {dr = -1, dc = 0},   -- 上
        {dr = -1, dc = 1},   -- 右上
        {dr = 0, dc = -1},   -- 左
        {dr = 0, dc = 1},    -- 右
        {dr = 1, dc = -1},   -- 左下
        {dr = 1, dc = 0},    -- 下
        {dr = 1, dc = 1}     -- 右下
    }
    
    for _, dir in ipairs(directions) do
        local nr = row + dir.dr
        local nc = col + dir.dc
        
        -- 检查边界
        if nr >= 1 and nr <= LevelTileConfig.GRID_SIZE.rows and
           nc >= 1 and nc <= LevelTileConfig.GRID_SIZE.cols then
            local neighborIndex = LevelTileConfig.getTileIndex(nr, nc)
            table.insert(neighbors, {
                row = nr,
                col = nc,
                index = neighborIndex,
                position = LevelTileConfig.tilePositions[neighborIndex]
            })
        end
    end
    
    return neighbors
end

-- 获取切片索引
function LevelTileConfig.getTileIndex(row, col)
    -- 行号从上到下：第1行在最上面
    return (row - 1) * LevelTileConfig.GRID_SIZE.cols + col
end

-- 根据世界坐标获取切片
function LevelTileConfig.getTileByPosition(x, y)
    -- 计算列索引（从左到右）
    local col = math.floor(x / LevelTileConfig.TILE_SIZE.width) + 1
    
    -- 计算行索引（从上到下）
    -- y=0在底部，y=8000在顶部
    -- 行号 = 5 - floor(y / 1600)
    local row = LevelTileConfig.GRID_SIZE.rows - math.floor(y / LevelTileConfig.TILE_SIZE.height)
    
    -- 边界检查
    col = math.max(1, math.min(col, LevelTileConfig.GRID_SIZE.cols))
    row = math.max(1, math.min(row, LevelTileConfig.GRID_SIZE.rows))
    
    return row, col
end

-- 根据世界坐标获取切片信息
function LevelTileConfig.getTileInfoByPosition(x, y)
    local row, col = LevelTileConfig.getTileByPosition(x, y)
    local index = LevelTileConfig.getTileIndex(row, col)
    return LevelTileConfig.tilePositions[index]
end

-- 检查坐标是否在有效范围内
function LevelTileConfig.isPositionInLevel(x, y)
    return x >= 0 and x <= LevelTileConfig.LEVEL_SIZE.width and
           y >= 0 and y <= LevelTileConfig.LEVEL_SIZE.height
end

-- 获取角色的初始位置（05_01左侧出生）
function LevelTileConfig.getInitialPlayerPosition()
    print("====================================")
    print("计算玩家初始位置")
    print("目标：在05_01（第5行第1列）左下角出生")
    print("====================================")
    
    -- 明确要在 05_01（第5行第1列）出生
    local targetRow = 5
    local targetCol = 1
    
    -- 获取切片索引
    local tileIndex = LevelTileConfig.getTileIndex(targetRow, targetCol)
    print(string.format("目标位置：%02d_%02d", targetRow, targetCol))
    print(string.format("计算得到的切片索引：%d", tileIndex))
    
    -- 从映射表获取切片信息
    local tileInfo = LevelTileConfig.tilePositions[tileIndex]
    
    if not tileInfo then
        print("错误：未找到05_01切片信息")
        print("检查切片位置映射表...")
        
        -- 输出所有切片信息用于调试
        for idx = 1, LevelTileConfig.TOTAL_TILES do
            local info = LevelTileConfig.tilePositions[idx]
            if info then
                print(string.format("  切片索引 %d: 行=%d, 列=%d, 文件=%s",
                    idx, info.row, info.col, info.filename))
            end
        end
        
        -- 尝试找到第一个可用的切片
        for idx = 1, LevelTileConfig.TOTAL_TILES do
            local info = LevelTileConfig.tilePositions[idx]
            if info then
                tileInfo = info
                print(string.format("使用备用切片：行%d列%d", info.row, info.col))
                break
            end
        end
    else
        print(string.format("找到目标切片：行=%d, 列=%d", tileInfo.row, tileInfo.col))
        print(string.format("切片坐标：x=%.1f, y=%.1f", tileInfo.x, tileInfo.y))
        print(string.format("世界坐标：worldX=%.1f, worldY=%.1f", tileInfo.worldX, tileInfo.worldY))
        print(string.format("地面高度：groundY=%.1f", tileInfo.groundY))
        print(string.format("切片文件：%s", tileInfo.filename))
    end
    
    if not tileInfo then
        print("错误：无法找到任何切片，使用默认位置")
        return {x = 1200, y = 1000}
    end
    
    -- 验证确实是05_01
    if tileInfo.row ~= 5 or tileInfo.col ~= 1 then
        print(string.format("警告：找到的切片是 %02d_%02d，不是05_01", 
            tileInfo.row, tileInfo.col))
    end
    
    -- 计算出生位置：在切片左侧离边界100像素，在地面之上150像素
    local startX = tileInfo.leftBound + 100
    local startY = tileInfo.groundY + 150
    
    print(string.format("最终出生位置：x=%.1f, y=%.1f", startX, startY))
    print("====================================")
    
    return {
        x = startX,
        y = startY
    }
end

-- 获取关卡边界（用于相机和物理边界）
function LevelTileConfig.getLevelBounds()
    return {
        left = 0,
        right = LevelTileConfig.LEVEL_SIZE.width,
        top = LevelTileConfig.LEVEL_SIZE.height,
        bottom = 0,
        width = LevelTileConfig.LEVEL_SIZE.width,
        height = LevelTileConfig.LEVEL_SIZE.height
    }
end

-- 获取切片的地面平台信息
function LevelTileConfig.getTileGroundPlatform(row, col)
    local index = LevelTileConfig.getTileIndex(row, col)
    local tileInfo = LevelTileConfig.tilePositions[index]
    if not tileInfo then return nil end
    
    return {
        x = tileInfo.leftBound,
        y = tileInfo.groundY,
        width = LevelTileConfig.TILE_SIZE.width,
        height = 50,  -- 地面厚度
        row = row,
        col = col
    }
end

-- 获取所有地面平台
function LevelTileConfig.getAllGroundPlatforms()
    local platforms = {}
    
    for row = 1, LevelTileConfig.GRID_SIZE.rows do
        for col = 1, LevelTileConfig.GRID_SIZE.cols do
            local platform = LevelTileConfig.getTileGroundPlatform(row, col)
            if platform then
                table.insert(platforms, platform)
            end
        end
    end
    
    return platforms
end

-- 验证文件是否存在
function LevelTileConfig.verifyTileFiles()
    local Content = require("Content")
    local missingFiles = {}
    
    print("====================================")
    print("验证关卡切片文件")
    print("====================================")
    
    local foundCount = 0
    for row = 1, LevelTileConfig.GRID_SIZE.rows do
        for col = 1, LevelTileConfig.GRID_SIZE.cols do
            local filename = LevelTileConfig.BASE_PATH .. string.format(LevelTileConfig.TILE_NAME_PATTERN, row, col)
            if Content:exist(filename) then
                foundCount = foundCount + 1
                if foundCount <= 5 then  -- 只显示前5个找到的文件
                    print(string.format("✓ 文件存在: %s", filename))
                end
            else
                table.insert(missingFiles, filename)
                print(string.format("✗ 文件不存在: %s", filename))
            end
        end
    end
    
    print("====================================")
    if #missingFiles > 0 then
        print(string.format("验证结果：找到 %d 个文件，缺失 %d 个文件", foundCount, #missingFiles))
        return false, missingFiles
    else
        print(string.format("✓ 所有 %d 个切片文件验证通过", foundCount))
        return true
    end
end

return LevelTileConfig